/**
*
*/
<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: labelPath }">{{labelTitle}}</el-breadcrumb-item>
      <el-breadcrumb-item>标签设置</el-breadcrumb-item>
    </el-breadcrumb>
    <!--    <NoPermission-->
    <!--      v-if="!authFilter(permissionObj, 'index')">-->
    <!--    </NoPermission>-->

    <div class="mgt20 relative">

      <!-- table标签 -->
      <el-tabs v-model="activeTabsValue" type="card" @tab-click="handleClick">
        <el-tab-pane
           v-for="(item, index) in activeTabs"
           :key="item.name"
           :label="item.label"
           :name="item.name">
          <div class="relative between-box">
            <div>

            </div>
            <el-button size="small" type="primary" icon="el-icon-plus"
              @click="handleEdit(null, {},true, item.label)">
              添加
            </el-button>
          </div>
          <div class="relative mgt16">
            <el-table
              size="small"
              :data="listData"
              highlight-current-row
              v-loading="loading"
              border
              element-loading-text="拼命加载中"
              style="width: 100%;"
              ref="multipleTable">
              <el-table-column
                prop="selection"
                align="center"
                type="selection"
                width="60">
              </el-table-column>
              <el-table-column align="center" prop="type" label="类型" min-width="100px">
              </el-table-column>
              <el-table-column align="center" prop="label" :label="tableLabel" min-width="200px">
              </el-table-column>
              <el-table-column align="center" label="操作" min-width="120" fixed="right">
                <template slot-scope="scope"
                          v-if="listData&&listData.length>0">
                  <el-button size="mini" type="primary" @click="handleEdit(scope.index,scope.row,false, item.label)">修改</el-button>
                  <el-button size="mini" type="danger" @click="deleteColumn(scope.$index, scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>
      <!-- 分页组件 -->
      <Pagination
        v-if="['quickreply'].includes(activeTabsValue)"
        v-bind:child-msg="pageparm"
        @callFather="callFather"></Pagination>

    </div>

    <!-- 编辑界面 -->
    <el-dialog
      :title="title"
      :visible.sync="editFormVisible"
      :width="['language','quickreply'].includes(activeTabsValue)?'60%':'30%'"
      @close="closeDialog('editForm')"
      style="margin-left: 200px;">
      <el-form
        class="edit-class"
        :label-width="['language','quickreply'].includes(activeTabsValue)?'120px':'80px'"
        :model="editForm" :rules="rules" ref="editForm">
        <template v-if="['language'].includes(activeTabsValue)">
          <el-row>
            <el-col :span="12">
              <el-form-item label="语言标签" prop="label">
                <el-input size="small" v-model="editForm.label" auto-complete="off" placeholder="请输入语言标签"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="语言标识" prop="value">
                <el-input size="small" v-model="editForm.value" auto-complete="off" placeholder="请输入语言标识"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
<!--          <el-row>-->
<!--            <el-col :span="24">-->
<!--              <el-form-item label="默认发布说明" prop="">-->
<!--                <custom-quill-editor-->
<!--                  v-if="editFormVisible"-->
<!--                  :content="editForm.content"-->
<!--                  @onEditorChange="onEditorChange">-->
<!--                </custom-quill-editor>-->
<!--              </el-form-item>-->
<!--            </el-col>-->
<!--          </el-row>-->
        </template>
        <template v-else-if="['quickreply'].includes(activeTabsValue)">
          <el-row>
            <el-col :span="24">
              <el-form-item label="快捷回复" prop="label">
<!--                <el-input-->
<!--                  size="small"-->
<!--                  v-model="editForm.label"-->
<!--                  auto-complete="off"-->
<!--                  placeholder="请输入快捷回复"-->
<!--                  type="textarea"-->
<!--                  :autosize="{ minRows: 3, maxRows: 4}"-->
<!--                  :maxlength="400"-->
<!--                  show-word-limit>-->
<!--                </el-input>-->
                <ClearableTextInput
                  :rows="4"
                  :autosize="{ minRows: 3, maxRows: 4}"
                  placeholder="请输入快捷回复"
                  v-model="editForm.label"
                  :values="editForm.label"
                  :clearable="true"
                  :maxlength="400"
                  :showWordLimit="true"
                  :input-change="inputChangeMethod"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </template>
        <template v-else>
          <el-form-item label="标签" prop="label">
            <el-input size="small" v-model="editForm.label" auto-complete="off" placeholder="请输入标签"
                      :maxlength="100" show-word-limit></el-input>
          </el-form-item>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog('editForm')">取消</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="submitForm('editForm')">保存</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {mapGetters, mapState} from "vuex";
import CustomQuillEditor from "@/components/custom-quill-editor.vue"
import Pagination from '../../components/Pagination'
import ClearableTextInput from '@/components/ClearableTextInput';

export default {
  // 注册组件
  components: {
    CustomQuillEditor,
    Pagination,
    ClearableTextInput,
  },
  data() {
    return {
      // 导出数据接口
      exportExcelRequest:'',
      //table标签
      activeTabsValue: 'brand',
      activeTabs: [],
      listData: [],
      loading: false, //是显示加载
      editFormVisible: false,
      title: '',
      tableLabel: '标签',
      editForm: {
        id: '',
        value: '',
        label: '',
        content: '',
      },
      isAdd: false,
      // rules表单验证
      rules: {
        label: [{ required: true, message: '请输入标签', trigger: 'blur' }],
        //语言标识
        value: [{ required: true, message: '请输入语言标识', trigger: 'blur' }],
      },
      brandList: [],
      modelList: [],
      channelList: [],
      questionCategoryList: [],
      quickreplyList: [],
      languageList: [],
      labelTitle: '',
      labelPath: '',
      formInline: {
        page: 1,
        pagenum: 10,
      },
      // 分页参数
      pageparm: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
    }
  },
  /**
   * 数据发生改变
   */

  /**
   * 创建完毕
   */
  created() {
    const vm = this
    // 获取路由参数
    let query = this.$route.query;
    if (query) {
      if(query.labelTitle){
        vm.labelTitle = query.labelTitle || ''
      }
      if(query.labelPath){
        vm.labelPath = query.labelPath || ''
      }
      if (query.fromPage == 'problemList'){
        vm.activeTabsValue = 'model'
        vm.activeTabs = [
          // {
          //   name: 'questionCategory',
          //   label: '问题模块',
          // },
          {
            name: 'model',
            label: '产品型号',
          },
          {
            name: 'language',
            label: '语言',
          }
        ]
      }else if(['feedbackList','technicalFeedbackeedback'].includes(query.fromPage)) {
        vm.activeTabsValue = 'quickreply'
        vm.activeTabs = [
          {
            name: 'quickreply',
            label: '快捷回复',
          }
          // {
          //   name: 'brand',
          //   label: '产品品牌',
          // },
          // {
          //   name: 'model',
          //   label: '产品型号',
          // },
          // {
          //   name: 'channel',
          //   label: '渠道',
          // },
          // {
          //   name: 'questionCategory',
          //   label: '问题模块',
          // }
        ]
      }else {
        vm.activeTabsValue = 'language'
        vm.activeTabs = [
          {
            name: 'language',
            label: '语言',
          }
        ]
      }
    }
    let param = {}
    if(['quickreply'].includes(vm.activeTabsValue)){
      param = this.formInline
    }
    vm.setLabel()
    vm.getList(param);
  },
  computed:{
    ...mapGetters(['userAuthList']),
    // ,permissionObj(){
    //   if(this.userAuthList&&this.userAuthList.length>0){
    //     return this.authListFilter(this.userAuthList,'invoices', 'BillingPlan')
    //   }
    // }
  },

  /**
   * 里面的方法只有被调用才会执行
   */
  methods: {
    setLabel(){
      const vm = this
      let labelObj = {
        // 'model': "产品型号",
        // 'channel': "渠道",
        // 'questionCategory': "问题模块",
        'quickreply': "快捷回复",
        'language': "语言",
      }
      vm.tableLabel = '标签'
      for(let path in labelObj){
        if(vm.activeTabsValue.indexOf(path) != -1){
          vm.tableLabel = labelObj[path]
          break
        }
      }
    },
    handleClick(tab) {
      const vm = this
      // if(vm.activeTabsValue == tab.name) return
      vm.activeTabsValue = tab.name
      if(vm.activeTabsValue == 'lanuage'){
        this.editForm = {
          type: '',
          label: '',
          value: '',
        }
        // this.operatorListGet()
      }else {
        this.editForm = {
          id: '',
          value: '',
          label: '',
        }
      }
      vm.setLabel()
      vm.getList();

    },
    //显示编辑(批量编辑)编辑界面
    handleEdit(index, row, isAdd, label) {
      const vm = this
      vm.editFormVisible = true
      vm.isAdd = isAdd;
      vm.title = (vm.isAdd ? '添加' : '修改') + label
      if (!vm.isAdd) {
        vm.editForm = {
          ...row
        }
      } else {
        vm.editForm = {}
      }
    },
    // 关闭编辑、增加弹出框
    clearValidate(formName){
      if(!this.$refs[formName]) return
      this.$refs[formName].clearValidate()
    },
    closeDialog(formName) {
      this.editFormVisible = false
      this.clearValidate(formName);
    },
    // resetForm(formName) {
    //   if(!this.$refs[formName]) return
    //   this.$refs[formName].resetFields();
    // },
    // // 关闭编辑、增加弹出框
    // closeDialog(formName) {
    //   // console.log('formName',formName)
    //   let fromObj = {
    //     'brand': this.resetForm(formName),
    //     'model': this.resetForm(formName),
    //     'channel': this.resetForm(formName),
    //     'questionCategory': this.resetForm(formName),
    //     'quickreply': this.resetForm(formName),
    //     'language': this.resetForm(formName),
    //   }
    //   for(let path in fromObj){
    //     if(formName.indexOf(path) != -1){
    //       // if(!fromObj[path]) break
    //       fromObj[path]
    //       break
    //     }
    //   }
    //   this.control[formName] = false
    // },
    // 显示编辑(批量编辑)编辑界面保存方法
    submitForm(editData) {
      const vm = this
      vm.$refs[editData].validate(valid => {
        if (valid) {
          let request = null
          let fromObj = null
          if(vm.isAdd){
            fromObj = {
              'brand': vm.apiUrl.phonebrandsAdd,
              'model': vm.apiUrl.phonemodelAdd,
              'channel': vm.apiUrl.channelAdd,
              'questionCategory': vm.apiUrl.questioncategoryAdd,
              'quickreply': vm.apiUrl.quickreplyAdd,
              'language': vm.apiUrl.languageAdd,
            }
          }else {
            fromObj = {
              'brand': vm.apiUrl.phonebrandsEdit,
              'model': vm.apiUrl.phonemodelEdit,
              'channel': vm.apiUrl.channelEdit,
              'questionCategory': vm.apiUrl.questioncategoryEdit,
              'quickreply': vm.apiUrl.quickreplyEdit,
              'language': vm.apiUrl.languageEdit,
            }
          }
          for(let path in fromObj){
            if(vm.activeTabsValue.indexOf(path) != -1){
              request = fromObj[path]
              break
            }
          }
          vm.editForm = {
            ...vm.editForm,
          }
          vm.openFullScreen()
          request(vm.editForm,"POST").then(res => {
            vm.closeFullScreen(vm.openFullScreen());
            const { code, msg } = res
            if (code != 0) {
              vm.showMessageMin({
                message: msg,
                type: 'error',
              })
            } else {
              vm.closeDialog('editForm')
              vm.showMessageMin({
                message: vm.title+'成功！',
                type: 'success',
              })
              vm.getList()
            }
          })
            .catch(err => {
              if(err&&err.isCancel) return
              vm.closeDialog('editForm')
              vm.closeFullScreen(vm.openFullScreen());
              vm.showMessageMin({
                message: vm.title+'失败，请稍后再试！',
                type: 'error',
              })
            })
        } else {
          return false
        }
      })
    },
    // 获取列表
    getList(parameter={}){
      const vm = this
      vm.loading = true
      let request = null
      let fromObj = {
        'brand': vm.apiUrl.phonebrandsList,
        'model': vm.apiUrl.phonemodelList,
        'channel': vm.apiUrl.channelListGet,
        'questionCategory': vm.apiUrl.questioncategoryListGet,
        'quickreply': vm.apiUrl.quickreplyListGet,
        'language': vm.apiUrl.languageListGet,
      }
      for(let path in fromObj){
        if(vm.activeTabsValue.indexOf(path) != -1){
          request = fromObj[path]
          break
        }
      }
      /***
       * 调用接口，注释上面模拟数据 取消下面注释
       */
      request(parameter).then(res => {
        let { code, msg } = res;
        if (code != 0) {
          this.$message({
            type: 'error',
            message: msg
          })
        }else {
          if(['quickreply'].includes(vm.activeTabsValue)){
            let { data:{
              list=[],totalnum=0
            } } = res;
            if(list){
              vm.listData = list
              // 分页赋值
              vm.pageparm.currentPage = vm.formInline.page
              vm.pageparm.pageSize = vm.formInline.pagenum
              vm.pageparm.total = totalnum
            }

          }else{
            let { data } = res;
            if(data){
              this.listData = data;
            }
          }
        }
      }).finally(()=>{
      vm.loading = false
      })
    },
    // 删除
    deleteColumn(index, row) {
      const vm = this
      vm.$confirm('确定要删除吗?', '信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const param = {
            type: row.type
          }
          vm.openFullScreen()
          let request = null
          let fromObj = {
            'brand': vm.apiUrl.phonebrandsDelete,
            'model': vm.apiUrl.phonemodelDelete,
            'channel': vm.apiUrl.channelDelete,
            'questionCategory': vm.apiUrl.questioncategoryDelete,
            'quickreply': vm.apiUrl.quickreplyDelete,
            'language': vm.apiUrl.languageDelete,
          }
          for(let path in fromObj){
            if(vm.activeTabsValue.indexOf(path) != -1){
              request = fromObj[path]
              break
            }
          }
          request(param,"POST")
            .then(res => {
              vm.closeFullScreen(vm.openFullScreen());
              const { code, msg } = res;
              console.log('code == 0', code == 0)
              if (code == 0) {
                vm.showMessageMin({
                  message: '已删除!',
                  type: 'success',
                })
                vm.getList()
              } else {
                vm.showMessageMin({
                  message: msg,
                  type: 'error',
                })
              }
            })
          })
        .catch(() => {
          vm.closeFullScreen(vm.openFullScreen());
          vm.showMessageMin({
            message: '已取消删除',
            type: 'info',
          })
        })
    },
    // 分页插件事件
    callFather(parm) {
      const vm = this
      vm.formInline = {
        ...vm.formInline,
        page: parm.currentPage,
        pagenum: parm.pageSize
      }
      vm.getList(vm.formInline)
    },
    inputChangeMethod() {
      console.log('input changed')
    },
    // 默认发布说明
    onEditorChange(e){
      const vm = this
      vm.editForm = {
        ...vm.editForm,
        content: e.content || ''
      }
    },

  }
}
</script>

<style lang="less" scoped>
// 内容主体高度
/deep/ .ql-toolbar.ql-snow + .ql-container.ql-snow{
  min-height: 250px;
}
/deep/ .ql-snow .ql-color-picker .ql-picker-label, .ql-snow .ql-icon-picker .ql-picker-label{
  display: flex;
  align-items: center;
}
/deep/ .ql-snow .ql-picker{
  height: 100%;
}
</style>
